package com.wx.md.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.wx.sftp.SaasFtp;
import com.wx.sftp.config.SaasFtpConf;
import com.wx.sftp.share.SaasDir;
import com.wx.sftp.utils.IOUtils;
import com.wx.sftp.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: 请详述
 * @Author: 刘畅
 * @CreateDate: 2020/10/15 16:25
 * @Version: 1.0
 */
@RestController
public class FileUploadController {
    @Autowired
    private SaasFtpConf conf;
    @Autowired
    private  SaasFtp saasFtp;


    /**
     * 上传
     *
     * @param base64Code
     * @param fileType
     * @return
     */
    @RequestMapping("/upload/image")
    public R<String> upload(String base64Code, String fileType){
        if(fileType.equals("png")||fileType.equals("jpg")||fileType.equals("gif")||fileType.equals("jepg")) {
            String fileName = RandomUtils.randomDateId() + "." + fileType;
            InputStream inputStream = IOUtils.base64ToInputStream(base64Code);
            return R.ok(saasFtp.upload(inputStream, SaasDir.IMAGES, fileName));
        }else{
            return R.failed("图片格式错误");
        }
    }

    /**
     * 删除图片url
     */
    @RequestMapping("/image/delete")
    public R<String> deleteImageUrl(String imageUrl){
       Boolean result =  saasFtp.deleteFileByUrl(imageUrl);
       if(result){
           return R.ok("删除成功！");
       }else{
           return R.ok("删除失败！");
       }
    }

    /**
     * 上传apk
     *
     * @return
     */
    @RequestMapping("/upload/apk")
    public R<String> uploadapk(MultipartFile file){
        try {
            String fileName = file.getOriginalFilename();// 获取到上传文件的名字
            InputStream inputStream =  file.getInputStream();
            int  index  = fileName.lastIndexOf(".");
            String newFileName = RandomUtils.randomDateId() + fileName.substring(index);
            String videoUrl =   saasFtp.upload(inputStream,SaasDir.APK,newFileName);
            return R.ok(videoUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok("");
    }



}
